package eppic.pkg;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.app.*;
import android.content.*;
import android.widget.TextView;
import android.widget.TimePicker;
import android.os.Handler;
import java.text.SimpleDateFormat;
import java.text.DecimalFormat;
import java.util.Calendar;
import android.app.TimePickerDialog;
import java.util.Date;
import java.text.DateFormat;


public class ClockedInActivity extends Activity {
	
	private static final int BACKGROUND_ID = 1;
	private Handler mHandler = new Handler();
	public String project_name;
	public long start_time;
	public float rate;
	public int is_project;
	public int parent_id;
	static final int TIME_DIALOG_ID = 0;
	private int mHour;
    private int mMinute;
	private int mDay;
    private int mMonth;
	private int mYear;
	
	public NotificationManager mNotificationManager;
	public Notification notification = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.clockedin);
        Bundle extras = getIntent().getExtras();
        
        //get StartTime
        start_time = extras.getLong("start_time");
        TextView timer = (TextView) findViewById(R.id.timer);
        
        //Get Type and set Name
        int id = extras.getInt("client_id");
        TextView task_name = (TextView) findViewById(R.id.task);
        
        if(id != 0)
        {
        	Client client = new Client(id, this);
        	project_name = client.company;
        	rate = client.rate;
        	parent_id = id;
        	is_project = 0;
        }
        else
        {
        	id = extras.getInt("project_id");
        	Project project = new Project(id, this);
        	project_name = project.name;
        	rate = project.rate;
        	parent_id = id;
        	is_project = 1;
        }
        task_name.setText(project_name);
        
        Runnable updateTimer = new Runnable() {
        	public void run() {
    		   long millis = System.currentTimeMillis() - start_time;
    	       int seconds = (int) (millis / 1000);
    	       int minutes = seconds / 60;
    	       int hours = minutes / 60;
    	       minutes = minutes % 60;
    	       seconds = seconds % 60;
    	       
    	       DecimalFormat twoDForm = new DecimalFormat("#.##");
    	       float floating_millis = (float) millis;
    	       float hoursDecimalValue = rate*(floating_millis/3600000);
    	       
    	       TextView timer = (TextView) findViewById(R.id.timer);
    	       timer.setText(String.format("%d:%02d:%02d", hours, minutes, seconds));
    	       TextView moneyEarned = (TextView) findViewById(R.id.moneyearned);
    	       
    	       if(hoursDecimalValue > 0.00999)
    	    	   moneyEarned.setText(String.format("Money Earned: $"+twoDForm.format(hoursDecimalValue)));
    	    	
    	       /* TODO show the current time and money earned without creating a notification on resume.
    	       if(notification != null)//Running in Background
    	       {
    	    	   //Update Notification
    	    	   Context context = getApplicationContext();
    	    	   notification.setLatestEventInfo(context, "Clocked In: "+project_name, String.format("$"+twoDForm.format(hoursDecimalValue)), notification.contentIntent);
    	    	   mNotificationManager.notify(BACKGROUND_ID, notification);
    	       }*/
    	    	   
    	       
    	       
    	       mHandler.postDelayed(this, 1000);
    	       
        	}
       };
        
       mHandler.removeCallbacks(updateTimer);
       mHandler.postDelayed(updateTimer, 1000);
    }
    
    public void clockOut(View view)
    {
    	long end = System.currentTimeMillis();
    	Log log = new Log(parent_id, is_project, start_time, end);
    	Context context = getApplicationContext();
    	if(log.save(context))
    	{
    		Toast.makeText(getApplicationContext(), "Clock Out Successful", Toast.LENGTH_SHORT).show();
    		finish();
    	}
    	else
    	{
    		Toast.makeText(getApplicationContext(), "ERROR: Failed to save log.", Toast.LENGTH_SHORT).show();
    	}
    
    }
    
    public void clockOutAt(View view)
    {
        final Calendar c = Calendar.getInstance();
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mMonth = c.get(Calendar.MONTH) + 1;
        mYear = c.get(Calendar.YEAR);

    	showDialog(TIME_DIALOG_ID);
    }
    
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this,
                    mTimeSetListener, mHour, mMinute, false);
        }
        return null;
    }
    
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
    	    new TimePickerDialog.OnTimeSetListener() {
    	        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    	        	/*TODO work out days here: if((hourOfDay == mHour && minute < mMinute) || (hourOfDay < mHour))
    	        	{
    	        		mDay++;
    	        	}*/
    	            mHour = hourOfDay;
    	            mMinute = minute;
    	            String dateString = ""+mMonth+"/"+mDay+"/"+mYear+" "+mHour+":"+mMinute; 
    	             
    	            Date date;
    	            DateFormat formatter = new SimpleDateFormat("MM/dd/yy HH:m");
    	            try{
    	                date = (Date)formatter.parse(dateString);
    	                long end = date.getTime();
    	             
	    	            Log log = new Log(parent_id, is_project, start_time, end);
	    	         	Context context = getApplicationContext();
	    	         	if(log.save(context))
	    	         	{
	    	         		Toast.makeText(getApplicationContext(), "Clock Out Successful", Toast.LENGTH_SHORT).show();
	    	         		finish();
	    	         	}
	    	         	else
	    	         	{
	    	         		Toast.makeText(getApplicationContext(), "ERROR: Failed to save log.", Toast.LENGTH_SHORT).show();
	    	         	}
    	             
    	            }
    	            catch(Exception e)
    	            {
    	            	Toast.makeText(getApplicationContext(), "Failed to Clock out.", Toast.LENGTH_LONG).show();
    	            }
    	        }

    	    };
    
    public void runInBg(View view)
    {
    	//Create Notification
    	String ns = Context.NOTIFICATION_SERVICE;
    	mNotificationManager = (NotificationManager) getSystemService(ns);
    	
    	int icon = R.drawable.icon;
    	CharSequence tickerText = "Clocked In: "+project_name;
    	long when = System.currentTimeMillis();

    	notification = new Notification(icon, tickerText, when);
    	notification.flags = 16;
    	
    	Context context = getApplicationContext();
    	CharSequence contentTitle = "Clocked In: "+project_name;
    	CharSequence contentText = "";
    	Intent notificationIntent = new Intent(this, DummyActivity.class);
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    	
    	notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    	mNotificationManager.notify(BACKGROUND_ID, notification);
    	
    	//Go to Home Screen
    	Intent startMain = new Intent(Intent.ACTION_MAIN);
    	startMain.addCategory(Intent.CATEGORY_HOME);
    	startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	startActivity(startMain);
    }
    
    //When Back is pressed
    @Override
    public void onBackPressed() {
    	backMenu();
    }

    //Back Menu
    public void backMenu()
    {
    	final CharSequence[] items = {"Clock Out", "Clock Out At...", "Run Time Tracker in Background", "Don't Save This Log"};
    	
    	AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
        alt_bld.setItems(items, new DialogInterface.OnClickListener() {
       	    public void onClick(DialogInterface dialog, int item) {
       	    	if(items[item] == "Clock Out")
       	    	{
       	    		clockOut(null);
       	    	}
       	    	if(items[item] == "Clock Out At...")
       	    	{
       	    		clockOutAt(null);
       	    	}
       	    	if(items[item] == "Run Time Tracker in Background")
       	    	{
       	    		runInBg(null);
       	    	}
       	    	if(items[item] == "Don't Save This Log")
       	    	{
       	    		finish();
       	    	}
       	    }
       	});
        AlertDialog alert = alt_bld.create();
        // Title for AlertDialog
        alert.setTitle("WARNING: \nThis Log Will Not be Saved.");
        alert.show();
    }
    
}